/*
 * @Description: 
 * @Author: 史迪仔
 * @Date: 2024-11-19 11:33:01
 * @LastEditors: 史迪仔
 * @LastEditTime: 2024-11-19 15:19:17
 */
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;


public class DruidTest {
    @Test
    public void test(){
        Connection conn=null;
        //声明操作对象
        //1.Statement - 容易被sql注入
        //2.PreparedStatement
        PreparedStatement pstmt = null;
        //声明结果集对象
        ResultSet rs=null;
        //创建集合
        List<User> list=new ArrayList();
        //1.加载配置文件
        Properties properties=new Properties();
        InputStream iStream=DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(iStream);
            // properties.forEach((k,v)->System.out.println(k+":"+v));
            //2.获取连接池对象
            DataSource dataSource= DruidDataSourceFactory.createDataSource(properties);
            conn=dataSource.getConnection();
            System.out.println("conn:"+conn);
            //3.获取操作对象
            //3.1 准备sql语句- 查询id为2的user
            String sql="select * from t_user where id=?";
            pstmt=conn.prepareStatement(sql);
            pstmt.setInt(1,2);
            //4.执行查询语句
            rs=pstmt.executeQuery();
            while (rs.next()) {
                //获取返回值
                int id=rs.getInt(1);
                String name=rs.getString(2);
                //String name=rs.getString("name");
                String password=rs.getString("password");
                int age=rs.getInt("age");
                // System.out.println(id+name+password+age);
                //将查询结果转换为对象
                User u=new User(id,name,password,age);
                System.out.println(u);
                //将查询结果存放到list中 输出这个list
                list.add(u);
            }
            System.out.println(list);
            System.out.println(list.size());
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        
    }
}
